<template>
  <div>
    <x-header style="background-color:#10aeff;">角色管理</x-header>
    <!-- 操作按钮组 -->
    <divider>操作</divider>
    <div style="margin: 0 15px;">
      <x-button mini plain @click.native="addfun">新增</x-button>
      <x-button v-if="checked" mini type="primary" @click.native="updatefun">修改</x-button>
      <x-button v-if="checked" mini type="warn" class="jbtn" @click.native="jurisdictionfun">权限</x-button>
      <x-button v-if="checked" mini type="warn" class="rbtn" @click.native="userfun">用户</x-button>
      <x-button v-if="checked" mini type="warn" @click.native="delfun">删除</x-button>
    </div>
    <!-- /操作按钮组 -->

    <checklist ref="demoObject" title="角色信息" :max="1" :options="keydata" v-model="checkedValue" @on-change="checkeds"></checklist>

    <!-- 新增角色窗体 -->
    <div v-transfer-dom>
      <confirm v-model="addshow" title="新增角色" @on-confirm="onConfirmAdd">
        <group>
          <x-input align="left" title="角色名称" v-model="obj.role_name"></x-input>
        </group>
      </confirm>
    </div>
    <!-- /新增角色窗体 -->

    <!-- 修改角色窗体 -->
    <div v-transfer-dom>
      <confirm v-model="updateshow" title="修改角色" @on-confirm="onConfirmUpdate">
        <group>
          <x-input align="left" title="ID" disabled v-model="obj.id"></x-input>
          <x-input align="left" title="角色名称" v-model="obj.role_name"></x-input>
          <!-- <x-textarea title="详细信息" placeholder="请填写详细信息" :show-counter="false" :rows="3"></x-textarea> -->
        </group>
      </confirm>
    </div>
    <!-- /修改角色窗体 -->

    <!-- 删除角色窗体 -->

    <div v-transfer-dom>
      <confirm v-model="delshow" title="删除角色" @on-confirm="onConfirmDel">
        <p style="text-align:center;">确认要删除角色: {{ obj.role_name }}？</p>
      </confirm>
    </div>
    <!-- /删除角色窗体 -->

    <!-- 分配权限窗体 -->

    <div v-transfer-dom>
      <!-- <confirm v-model="jurisdictionshow" title="删除角色" @on-confirm="onConfirmDel">
        <checklist ref="demoObject" title="角色信息" :options="jurisdictionKeyData" v-model="checkedValue" @on-change="checkeds"></checklist>
      </confirm> -->
      <popup v-model="jurisdictionshow" position="bottom" max-height="50%">
        <checklist ref="demoObject" title="分配权限" :options="jurisdictionKeyData" v-model="jurisdictionChecked"></checklist>
        <div style="padding: 15px;">
          <x-button @click.native="updateJurisdiction" mini plain type="primary"> 确 定</x-button>
          <x-button @click.native="jurisdictionshow = false" mini plain type="warn" style="align:right"> 取 消 </x-button>

        </div>
      </popup>
    </div>
    <!-- /分配权限窗体 -->

    <!-- 分配用户窗体 -->

    <div v-transfer-dom>
      <!-- <confirm v-model="jurisdictionshow" title="删除角色" @on-confirm="onConfirmDel">
        <checklist ref="demoObject" title="角色信息" :options="jurisdictionKeyData" v-model="checkedValue" @on-change="checkeds"></checklist>
      </confirm> -->
      <popup v-model="usershow" position="bottom" max-height="50%">
        <checklist ref="demoObject" title="分配用户" :options="userKeyData" v-model="userChecked"></checklist>
        <div style="padding: 15px;">
          <x-button @click.native="updateUser" mini plain type="primary"> 确 定</x-button>
          <x-button @click.native="usershow = false" mini plain type="warn" style="align:right"> 取 消 </x-button>

        </div>
      </popup>
    </div>
    <!-- /分配用户窗体 -->

    <toast v-model="handleSuccess" :time="1000">操作成功</toast>

  </div>
</template>

<script>
import {
  Cell,
  CellBox,
  XButton,
  Group,
  LoadMore,
  XHeader,
  PopupPicker,
  Divider,
  XTable,
  TransferDom,
  Popup,
  Checklist,
  Alert,
  XInput,
  Confirm,
  Selector,
  XNumber,
  XTextarea,
  Datetime,
  Toast
} from "vux";
import Icon from "vue-awesome/components/Icon";
import "vue-awesome/icons/folder-open";
import axios from "axios";
export default {
  directives: {
    TransferDom
  },
  components: {
    Popup,
    Cell,
    CellBox,
    XButton,
    Group,
    LoadMore,
    XHeader,
    Icon,
    PopupPicker,
    Divider,
    XTable,
    Checklist,
    Alert,
    XInput,
    Confirm,
    Selector,
    XNumber,
    XTextarea,
    Datetime,
    Toast
  },
  data() {
    return {
      data: [],
      keydata: [],
      checkedValue: [],
      checked: false,
      obj: {},
      addshow: false,
      updateshow: false,
      delshow: false,
      jurisdictionshow: false,
      jurisdictionData: [],
      jurisdictionKeyData: [],
      jurisdictionChecked: [],
      jurisdiction_role_temp: [],
      handleSuccess: false,
      usershow: false,
      userChecked: [],
      userKeyData: [],
      userData: [],
      userTemp: []
    };
  },
  created() {
    this.getInfo();
  },
  methods: {
    async updateJurisdiction() {
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      let info = null;

      try {
        info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `mutation{role_jurisdiction_ChangeOne(id:${this.obj.id})}`
        });
      } catch (error) {
        console.error(error);
      }
      let temp = `[`;
      for (const item of this.jurisdictionChecked) {
        temp += `{role_id:${this.obj.id},jurisdiction_id:${item}},`;
      }
      temp.substr(0, temp.Length - 1);
      temp += "]";
      info = await instance.post(`http://192.168.10.19:4000/graphql`, {
        query: `mutation{
                    role_jurisdiction_ChangeTow(record:${temp}){jurisdiction_id}
                  }`
      });
      this.jurisdictionshow = false;
    },
    async jurisdictionfun() {
      this.jurisdictionshow = true;
      let index = this.checkedValue[0] - 1;
      this.obj.id = this.data[index].id;
      this.obj.role_name = this.data[index].role_name;

      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      let info = null;
      try {
        info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `{Role_jurisdiction_By_Role(role_id:${this.obj.id}){
                    id
                    role_id
                    jurisdiction_id
                    },
                    jurisdictionList{
                    Jurisdiction_name,
                    Jurisdiction_path,
                    Jurisdiction_type,
                    type,
                    id
                  }}`
        });
        this.jurisdictionData = [];
        this.jurisdictionData = info.data.data.jurisdictionList;
        this.jurisdiction_role_temp = [];
        this.jurisdiction_role_temp = info.data.data.Role_jurisdiction_By_Role;
        // 因为组件需要key，而原始数据没有，调用此方法增加
        this.getKeyjurisdictionData();
      } catch (error) {
        console.error(error);
      }
    },
    delfun() {
      this.delshow = true;
      let index = this.checkedValue[0] - 1;
      this.obj.id = this.data[index].id;
      this.obj.role_name = this.data[index].role_name;
    },
    updatefun() {
      this.updateshow = true;
      let index = this.checkedValue[0] - 1;
      this.obj.id = this.data[index].id;
      this.obj.role_name = this.data[index].role_name;
    },
    checkeds() {
      this.jurisdictionChecked = [];
      if (this.checkedValue.length == 0) {
        this.checked = false;
      } else {
        this.checked = true;
      }
    },
    addfun() {
      this.addshow = true;
      this.obj.role_name = "";
    },
    async userfun() {
      this.usershow = true;
      let index = this.checkedValue[0] - 1;
      this.obj.id = this.data[index].id;
      this.obj.role_name = this.data[index].role_name;

      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      let info = null;
      try {
        info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `{Role_User_By_Role(role_id:${this.obj.id}){
                    id,
                    role_id,
                    user_id
                  }
                  userList(department:"",company:"汉中分公司"){
                    id,
                    department,
                    company,
                    user_name,
                    user_code
                  }}`
        });
        this.userData = [];
        this.userData = info.data.data.userList;
        this.userTemp = [];
        this.userTemp = info.data.data.Role_User_By_Role;
        // 因为组件需要key，而原始数据没有，调用此方法增加
        this.getKeyUserData();
      } catch (error) {
        console.error(error);
      }
    },
    getKeyUserData() {
      this.userChecked = [];
      this.userKeyData = [];
      for (const item of this.userTemp) {
        this.userChecked.push(item.user_id);
      }

      for (let index = 0; index < this.userData.length; index++) {
        let temp = {
          key: this.userData[index].id,
          value: `${this.userData[index].company}|${
            this.userData[index].department
          }|${this.userData[index].user_name}|${this.userData[index].user_code}
          `
        };
        this.userKeyData.push(temp);
      }
    },
    async updateUser() {
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      let info = null;

      try {
        info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `mutation{role_user_ChangeOne(id:${this.obj.id})}`
        });
      } catch (error) {
        console.error(error);
      }
      let temp = `[`;
      for (const item of this.userChecked) {
        temp += `{role_id:${this.obj.id},user_id:${item}},`;
      }
      temp.substr(0, temp.Length - 1);
      temp += "]";
      info = await instance.post(`http://192.168.10.19:4000/graphql`, {
        query: `mutation{
                    role_user_ChangeTow(record:${temp}){user_id}
                  }`
      });
      this.usershow = false;
      this.handleSuccess = true;
    },
    async onConfirmDel() {
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      try {
        let info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `mutation{roleDel(id:${this.obj.id})}`
        });
        if (info.data.data.roleDel) {
          this.handleSuccess = true;
          this.checkedValue = [];
          this.getInfo();
        }
      } catch (error) {
        console.error(error);
      }
    },
    async onConfirmUpdate() {
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      try {
        let info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `mutation{roleUpdate(id:${this.obj.id},role_name:"${
            this.obj.role_name
          }")}`
        });
        if (info.data.data.roleUpdate) {
          this.handleSuccess = true;
          this.checkedValue = [];
          this.getInfo();
        }
      } catch (error) {
        console.error(error);
      }
    },
    async onConfirmAdd() {
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      try {
        let info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `mutation{
                  roleAdd(role_name:"${this.obj.role_name}"){role_name}}`
        });
        if (info.data.data.roleAdd.role_name) {
          this.handleSuccess = true;
          this.getInfo();
        }
      } catch (error) {
        console.error(error);
      }
    },
    async getInfo() {
      let instance = axios.create({
        headers: { "content-type": "application/json" }
      });
      try {
        let info = await instance.post(`http://192.168.10.19:4000/graphql`, {
          query: `{ roleList{
                    role_name
                    id
                  }}`
        });
        this.data = [];
        this.data = info.data.data.roleList;
        // 因为组件需要key，而原始数据没有，调用此方法增加
        this.getKeydata();
      } catch (error) {
        console.error(error);
      }
    },
    // 给原始数据增加key，因为0在组件中无法选中，所以+1，在使用时请-1，否则会越界
    getKeydata() {
      this.keydata = [];
      for (let index = 0; index < this.data.length; index++) {
        let temp = {
          key: index + 1,
          value: `${this.data[index].role_name} `
        };
        this.keydata.push(temp);
      }
    },
    getKeyjurisdictionData() {
      this.jurisdictionKeyData = [];
      this.jurisdictionChecked = [];

      for (const item of this.jurisdiction_role_temp) {
        this.jurisdictionChecked.push(item.jurisdiction_id);
      }

      for (let index = 0; index < this.jurisdictionData.length; index++) {
        let temp = {
          key: this.jurisdictionData[index].id,
          value: `${this.jurisdictionData[index].type ? "移动端" : "PC端"} --${
            this.jurisdictionData[index].Jurisdiction_name
          } `
        };
        this.jurisdictionKeyData.push(temp);
      }
    }
  }
};
</script>

<style scoped>
.jbtn {
  background-color: #ffbe00;
}
.jbtn:active {
  color: rgba(255, 255, 255, 0.6);
  background-color: #ffbe00 !important;
}
.rbtn {
  background-color: #10aeff;
}
.rbtn:active {
  color: rgba(255, 255, 255, 0.6);
  background-color: #10aeff !important;
}
.weui-dialog__bd .weui-cells_checkbox .weui-check_label .weui-cell__bd {
  text-align: left !important;
}
.weui-btn {
  margin-top: 15px;
}
</style>
